package com.baselibrary.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Created By Carl on 2020-07-31
 * 微信工具
 */
public class WxUtils {
    public static IWXAPI api;

    /**
     * 获取api
     *
     * @return
     */
    public static IWXAPI getApi() {
        return api;
    }

    /**
     * 注册到微信
     *
     * @param context
     */
    public static void regToWx(Context context) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(context, Config.WECHAT_APP_ID, false);
        // 将应用的appId注册到微信
        api.registerApp(Config.WECHAT_APP_ID);
    }

    public int QQ = 1;
    public int WX = 2;
    public int WX_Circle = 3;
    public int QQ_Zone = 4;

    public WxUtils(Context context, String path, int type) {
        if (type == QQ) {
            shareImage(context, path, new ShareItem("QQ", "com.tencent.mobileqq.activity.JumpActivity", "com.tencent.mobileqq"));
        }
        if (type == WX) {
            shareImage(context, path, new ShareItem("微信", "com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.mm"));
        }
        if (type == WX_Circle) {
            shareImage(context, path, new ShareItem("微信朋友圈", "com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.mm"));
        }
        if (type == QQ_Zone) {
            shareImage(context, path, new ShareItem("QQ空间", "com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.qq"));
        }
    }

    private void shareImage(Context context, String imageUrl, ShareItem share) {
        if (!share.packageName.isEmpty() && !isAvailable(context, share.packageName)) {
//            Toast.makeText(context, "请先安装 " + share.title, Toast.LENGTH_LONG).show();
            HKToastUtils.showToast("请先安装 " + share.title);
            return;
        }
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUrl);
        if (!share.packageName.isEmpty()) {
            shareIntent.setComponent(new ComponentName(share.packageName, share.activityName));
            context.startActivity(shareIntent);
        } else {
            context.startActivity(Intent.createChooser(shareIntent, Intent.ACTION_ALL_APPS));
        }

    }

    public boolean isAvailable(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> info = packageManager.getInstalledPackages(0);
        for (int i = 0; i < info.size(); i++) {
            if (info.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    private class ShareItem {
        String title, activityName, packageName;

        public ShareItem(String title, String activityName, String packageName) {
            this.title = title;
            this.activityName = activityName;
            this.packageName = packageName;
        }
    }

    /**
     * 分享图片到微信
     *
     * @param imgUrl
     * @param targetScene SendMessageToWX.Req.WXSceneSession 会话  SendMessageToWX.Req.WXSceneTimeline 朋友圈
     */
    public static void shareImageToWx(final String imgUrl, final int targetScene) {
        if (!TextUtils.isEmpty(imgUrl)) {
            //初始化 WXImageObject 和 WXMediaMessage 对象
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bmp = null;
                    WXMediaMessage msg = new WXMediaMessage();
                    try {
                        bmp = Glide.with(ContextUtils.getCurApplication())
                                .asBitmap()
                                .load(imgUrl)
                                .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                .get();
                        WXImageObject wxImageObject = new WXImageObject(bmp);
                        msg.mediaObject = wxImageObject;
                        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, (int) (bmp.getWidth() * 0.6), (int) (bmp.getHeight() * 0.6), false);
                        msg.thumbData = bmpToByteArray(thumbBmp, true);//封面图片，小于128k
                        bmp.recycle();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //构造一个Req
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = buildTransaction("img");
                    req.message = msg;
                    req.scene = targetScene;

                    //调用api接口，发送数据到微信
                    api.sendReq(req);
                }
            }).start();
        } else {
            HKToastUtils.showToast("分享图片地址不能为空");
        }
    }

    public static void shareToWxWeb(final String url, final String title, final String content, final String imgUrl, final int targetScene) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //初始化一个WXWebpageObject，填写url
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = url;

                //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = title;
                msg.description = content;
                Bitmap bmp = null;
                try {
                    bmp = Glide.with(ContextUtils.getCurApplication())
                            .asBitmap()
                            .load(imgUrl)
                            .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .get();
                    WXImageObject wxImageObject = new WXImageObject(bmp);
                    msg.mediaObject = wxImageObject;
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, (int) (bmp.getWidth() * 0.6), (int) (bmp.getHeight() * 0.6), false);
                    msg.thumbData = bmpToByteArray(thumbBmp, true);//封面图片，小于128k
                    bmp.recycle();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                req.scene = targetScene;

                //调用api接口，发送数据到微信
                api.sendReq(req);
            }
        }).start();

    }

    public static void shareWeb(final String imgUrl, String url, String title, String desc) {
        //初始化一个WXWebpageObject，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = desc;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bmp = null;
                try {
                    bmp = Glide.with(ContextUtils.getCurApplication())
                            .asBitmap()
                            .load(imgUrl)
                            .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .get();
                    WXImageObject wxImageObject = new WXImageObject(bmp);
                    msg.mediaObject = wxImageObject;
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, (int) (bmp.getWidth() * 0.6), (int) (bmp.getHeight() * 0.6), false);
                    msg.thumbData = bmpToByteArray(thumbBmp, true);//封面图片，小于128k
                    bmp.recycle();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        //req.userOpenId = getOpenId();
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 80, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 微信登录
     */
    public static void wxLogin() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
    }


    /**
     * 将网络图片加载到内存
     *
     * @param url
     * @return
     */
    public static byte[] getHtmlByteArray(final String url) {
        URL htmlUrl = null;
        InputStream inStream = null;
        try {
            htmlUrl = new URL(url);
            URLConnection connection = htmlUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将io流转为byte数组
        byte[] data = inputStreamToByte(inStream);
        if (data.length > '耀') {

            // 转换为bitmap
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

            // 获取压缩后的byte数组
            data = compressByQuality(bitmap, '耀', true);
        }
        return data;
    }

    /**
     * 将io流转为byte数组
     *
     * @param is
     * @return
     */
    public static byte[] inputStreamToByte(InputStream is) {
        try {
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                bytestream.write(ch);
            }
            byte imgdata[] = bytestream.toByteArray();
            bytestream.close();
            return imgdata;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 按质量压缩图片
     *
     * @param src         bitmap图片
     * @param maxByteSize 最大字节数
     * @param recycle
     * @return
     */
    public static byte[] compressByQuality(final Bitmap src, final long maxByteSize, final boolean recycle) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        src.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes;
        if (baos.size() <= maxByteSize) {
            bytes = baos.toByteArray();
        } else {
            baos.reset();
            src.compress(Bitmap.CompressFormat.JPEG, 0, baos);
            if (baos.size() >= maxByteSize) {
                bytes = baos.toByteArray();
            } else {
                // find the best quality using binary search
                int st = 0;
                int end = 100;
                int mid = 0;
                while (st < end) {
                    mid = (st + end) / 2;
                    baos.reset();
                    src.compress(Bitmap.CompressFormat.JPEG, mid, baos);
                    int len = baos.size();
                    if (len == maxByteSize) {
                        break;
                    } else if (len > maxByteSize) {
                        end = mid - 1;
                    } else {
                        st = mid + 1;
                    }
                }
                if (end == mid - 1) {
                    baos.reset();
                    src.compress(Bitmap.CompressFormat.JPEG, st, baos);
                }
                bytes = baos.toByteArray();
            }
        }
        if (recycle && !src.isRecycled()) src.recycle();
        return bytes;
    }


    public static String substringDes(String des) {
        if (des.length() >= 30) {
            des = des.substring(0, 30) + "......";
        }
        return des;
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}
